<script setup>
import { ref, onMounted, getCurrentInstance } from 'vue'

const Emit = defineEmits(['voiceEnd'])

const { appContext } = getCurrentInstance()
const config = appContext.config.globalProperties.$config

// 使用多个audio主要是为了提前预加载mp3文件，以后播放流畅

const obj = {
  Welcome: 0,
  OneAnswer: 1,
  MoreAnswer: 2,
  NoAnswer1: 3,
  NoAnswer2: 4,
  NoAnswer3: 5,
  MorePeople: 6
}

const voiceArr = ref([
  {
    name: 'Welcome',
    url: config.welcomeVoice
  }, {
    name: 'OneAnswer',
    url: config.singleAnswerVoice
  }, {
    name: 'MoreAnswer',
    url: config.multipleAnswerVoice
  }, {
    name: 'NoAnswer1',
    url: config.apologyVoice
  }, {
    name: 'NoAnswer2',
    url: config.apologyHintSecondVoice
  }, {
    name: 'NoAnswer3',
    url: config.apologyHintThreeVoice
  }, {
    name: 'MorePeople',
    url: config.timeoutVoice
  }
])

const voice = ref(new Map())

const voiceCallback = (name) => {
  voiceArr.value.forEach((item) => {
    // 循环遍历所有音频    正在播放的音频时间设置为0 并暂停
    if (!voice.value[obj[item.name]].ended) {
      voice.value[obj[item.name]].currentTime = 0
      voice.value[obj[item.name]].pause()
    }
  })

  if (name) {
    console.log('播放mp3', name)
    setTimeout(() => {
      voice.value.forEach(v => {
        if (v.getAttribute('data-id') === name) { v.play() }
      })
    }, 10)
  }
}

const toogleMuted = (value) => {
  voiceArr.value.forEach((item) => {
    voice.value[obj[item.name]].muted = value
  })
}

defineExpose({ voiceCallback, toogleMuted })

onMounted(() => {
  voiceArr.value.forEach((item) => {
    voice.value[obj[item.name]].muted = config.openVoice !== 1
    voice.value[obj[item.name]].addEventListener('ended', () => {
      console.log('mp3播放结束, 触发voiceEnd')
      Emit('voiceEnd')
    })
  })
})
</script>

<template>
  <div class="com-audio">
    <audio
      ref="voice"
      v-for="item in voiceArr"
      :data-id="item.name"
      :key="item.name"
      :src="item.url"
    />
  </div>
</template>

<style lang="less">
.com-audio {
  opacity: 0;
}
</style>
